package com.mirror.tk.core.sms.net.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.mirror.tk.core.sms.net.IRequestService;

public class HttpRequestServiceImpl implements IRequestService {

	private int socketTimeout = 10000;

	// 传输超时时间，默认30秒
	private int connectTimeout = 30000;

	// 请求器的配置
	private RequestConfig requestConfig;

	// HTTP请求器
	private CloseableHttpClient httpClient;

	public HttpRequestServiceImpl() {
		httpClient = HttpClients.createDefault();
		requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
	}

	@Override
	public String post(String url, Map<String, String> param) throws IOException {
		HttpPost httpPost = new HttpPost(url);
		// 参数设置
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> en : param.entrySet()) {
			paramList.add(new BasicNameValuePair(en.getKey(), en.getValue()));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
		// 设置请求器的配置
		httpPost.setConfig(requestConfig);
		try {
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} finally {
			httpPost.abort();
		}
	}
	
}
